﻿namespace KeRui.Json.Converters
{
    using KeRui.Json;
    using System;
    using System.Globalization;

    public class AspNetAjaxDateTimeConverter : JsonConverter
    {
        public override bool CanConvert(Type valueType)
        {
            return typeof(DateTime).IsAssignableFrom(valueType);
        }

        public override object ReadJson(JsonReader reader, Type objectType)
        {
            string str = (string) reader.Value;
            return JavaScriptConvert.ConvertJavaScriptTicksToDateTime(Convert.ToInt64(str.Substring(1, str.Length - 2)));
        }

        public override void WriteJson(JsonWriter writer, object value)
        {
            DateTime dateTime = (DateTime) value;
            writer.WriteValue("@" + JavaScriptConvert.ConvertDateTimeToJavaScriptTicks(dateTime).ToString(null, CultureInfo.InvariantCulture) + "@");
        }
    }
}

